package org.gl.training.planner.dao;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;

import org.dbunit.database.DatabaseConnection;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.xml.FlatXmlDataSetBuilder;
import org.dbunit.operation.DatabaseOperation;
import org.gl.training.planner.model.DailyPlan;
import org.gl.training.planner.model.Task;
import org.gl.training.planner.model.User;
import org.gl.training.planner.model.UserHistory;
import org.gl.training.planner.model.UserTypes;
import org.hibernate.ejb.Ejb3Configuration;
import org.junit.After;
import org.junit.Before;

public class DefaultDaoTst {

	protected EntityManager entityManager;

	@Before
	public void init() throws Exception {	
		entityManager = createEntityManager();
		DatabaseOperation.CLEAN_INSERT.execute(getConnection(), getDataSet());
		
		entityManager.getTransaction().begin();
	}

	@After
	public void after() throws Exception {
		entityManager.getTransaction().rollback();
		DatabaseOperation.DELETE_ALL.execute(getConnection(), getDataSet());
	}

	protected EntityManager createEntityManager() throws IOException {
		Properties properties = getHibernateProperties();

		Ejb3Configuration cfg = new Ejb3Configuration();
		cfg.addProperties(properties);
		cfg.addAnnotatedClass(DailyPlan.class);
		cfg.addAnnotatedClass(Task.class);
		cfg.addAnnotatedClass(User.class);
		cfg.addAnnotatedClass(UserHistory.class);
		cfg.addAnnotatedClass(UserTypes.class);

		EntityManagerFactory factory = cfg.buildEntityManagerFactory();
		return factory.createEntityManager();
	}

	protected Properties getHibernateProperties() throws IOException {
		InputStream is = getClass().getClassLoader().getResourceAsStream(
				"hb.properties");
		Properties properties = new Properties();
		properties.load(is);
		return properties;
	}

	protected Connection createConnection() throws IOException,
			ClassNotFoundException, SQLException {
		Properties properties = getHibernateProperties();
		String url = properties.getProperty("hibernate.connection.url");
		String driver = properties
				.getProperty("hibernate.connection.driver_class");
		Class.forName(driver);
		return DriverManager.getConnection(url, null, null);

	}

	private IDatabaseConnection getConnection() throws Exception {
		IDatabaseConnection connection = new DatabaseConnection(
				createConnection());
		return connection;
	}

	private IDataSet getDataSet() throws Exception {
		InputStream is = getClass().getClassLoader().getResourceAsStream(
				"dbunit_data.xml");
		return new FlatXmlDataSetBuilder().build(is);
	}
}
